﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
	public class TakeAwayIntegeralSettingRepository : Repository<TakeAwayIntegeralSetting>, ITakeAwayIntegeralSettingRepository
	{
		protected override Expression<Func<TakeAwayIntegeralSetting, int>> PrimaryKeyExpression => r => r.Id;

		public TakeAwayIntegeralSettingRepository(ApiDBContent context) : base(context)
		{
		}

		protected override IEnumerable<TakeAwayIntegeralSetting> IncludeRelationships(IEnumerable<TakeAwayIntegeralSetting> entities, ApiDBContent db)
		{
			SetShopInfo(entities);

			return base.IncludeRelationships(entities, db);
		}

		private void SetShopInfo(IEnumerable<TakeAwayIntegeralSetting> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayIntegeralSettinRelationShipEnum.ShopInfo))
			{
				return;
			}

			var shopIds = entities.Select(r => r.ShopId).ToList();
			var dicShop = Context.TakeAwayShop.Where(r => shopIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r.Name);
			foreach (var entity in entities)
			{
				if (dicShop.TryGetValue(entity.ShopId, out string shopName))
				{
					entity.ShopName = shopName;
				}
			}
		}
	}
}
